package pl.un4giv3n.mightvsmagic.action;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import pl.un4giv3n.mightvsmagic.entity.User;
import pl.un4giv3n.mightvsmagic.entity.UserType;

/**
 * @author andrzejewskia
 * searches for user
 */
public class SearchUserAction extends PersistenceAction {

	private static final long serialVersionUID = 1L;
	/**
	 * user id to show
	 */
	private Long id;
	/**
	 * session user
	 */
	private User user;
	private String username;
	private UserType userType;

	@Override
	public String execute() {
		EntityManager entityManager = getEntityManager();
		user = getSessionUser(entityManager);
		if(user == null){
			addActionError("Zaloguj się");
			entityManager.close();
			return LOGIN;
		}
		User searchedUser = null;
		if(username == null || "".equals(username.trim())){
			 searchedUser = findRandomUser(entityManager);
		}else{
			searchedUser = findUserByParams(entityManager);
		}
		if(searchedUser == null){
			addActionError("Nie znaleziono gracza.");
			entityManager.close();
			return ERROR;
		}else{
			id = searchedUser.getId();
		}
		entityManager.close();
		return SUCCESS;
	}

	@SuppressWarnings("unchecked")
	private User findUserByParams(EntityManager em) {
		Query query = em.createNamedQuery("find.user.by.login");
		query.setParameter("login", username);
		List resultList = query.getResultList();
		if(resultList != null && !resultList.isEmpty()){
			User user = (User) resultList.get(0);
			if(userType == null || user.getUserType() == userType){
				return user;
			}
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	private User findRandomUser(EntityManager em) {
		Query query = null;
		if(userType == null){
			query = em.createNamedQuery("find.attackable.users");
			
		}else{
			query = em.createNamedQuery("find.attackable.users.with.type");
			query.setParameter("type", userType);
		}
		query.setParameter("time", System.currentTimeMillis() - ONE_HOUR);
		List resultList = query.getResultList();
		if(resultList != null && !resultList.isEmpty()){
			int id = (int)(Math.random() * resultList.size());
			return (User) resultList.get(id);
		}
		return null;
	}
	
	public User getUser() {
		return user;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public UserType getUserType() {
		return userType;
	}

	public void setUserType(String userType) {
		//set userType only for valid params, leave as null if "any" is selected on gui
		for (UserType type : UserType.values()) {
			if(type.name().equals(userType)){
				this.userType = type;
				break;
			}
		}
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}
}
